/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.klikmee.sms.chat.web.util;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 
 * @author makcro
 * 
 */

/*
 * Used to Lookup Spring managed beans in java POJO classes Spring
 * WebApplicationContext is automaticaly initialized after deployment of
 * application
 */
public class SpringBeansLookup {

	// convitiance constants representing bean names, used to retreive bean
	// instances
	private static WebApplicationContext applicationContext;
	private static ServletContext servletContext;
	private static Logger logger = Logger.getLogger(SpringBeansLookup.class);
	/*
	 * called after app deployment by servlet container.
	 * 
	 * @param servletContext current web app servlet context used to initialize
	 * spring webapplication context
	 */
	public static void init(ServletContext servletContext) {
		applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		SpringBeansLookup.servletContext = servletContext;
		logger.info("Spring beans lookup helper class initialized...");
	}

	/*
	 * Retreives spring managed based on name configured in spring xml
	 * configuration files. Example: UserRoleDAO userRoleDAO = (UserRoleDAO)
	 * SpringBeansLookup.getBean( SpringBeansLookup.USER_ROLE_DAO);
	 */
	public static Object getBean(String beanName) {
		return applicationContext.getBean(beanName);
	}

	public static <T extends Object> T getBean(Class<T> beanClass) {
		return applicationContext.getBean(beanClass);
	}

	public static ServletContext getServletContext() {
		return SpringBeansLookup.servletContext;
	}
}
